package com.yuanluludev.app.activity

import android.content.Intent
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.utils.BitmapUtils
import com.yuanluludev.app.R
import com.yuanluludev.app.bean.Person
import com.yuanluludev.imageloader.glide.GlideManager
import com.yuanluludev.lib_aop.Log
import com.yuanluludev.lib_aop.SingleClick
import com.yuanluludev.lib_base.base.BaseVMTwiceExitActivity
import com.yuanluludev.lib_base.bean.WinBean
import com.yuanluludev.lib_base.ext.toastTipMiddle
import com.yuanluludev.lib_base.utils.MMKVUtils
import com.yuanluludev.lib_pic.adapter.GridImageAdapter
import com.yuanluludev.lib_pic.adapter.NetImageAdapter
import com.yuanluludev.lib_pic.bean.PicSelectorType
import com.yuanluludev.lib_pic.utils.PicSelectorUtils
import com.yuanluludev.lib_utils.util.*
import com.yuanluludev.lib_xpopup.DragPhotoViewUtils
import com.yuanluludev.pgy.Pgy
import kotlinx.android.synthetic.main.activity_sample_main.*
import okhttp3.internal.applyConnectionSpec

class SampleActivity : BaseVMTwiceExitActivity<SampleViewModel>() {

    private var mAdapter: GridImageAdapter? = null
    private var netImageAdapter: NetImageAdapter? = null
    private var picData: ArrayList<LocalMedia> = ArrayList()

    private var netData: ArrayList<String> = ArrayList<String>().apply {
        add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2Ff%2F57a42b9002e19.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673423440&t=3e646b23ed5930e48b7bdec9c1cc4f8c")
        add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Flmg.jj20.com%2Fup%2Fallimg%2F1114%2F042421133312%2F210424133312-1-1200.jpg&refer=http%3A%2F%2Flmg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673423440&t=70f11140812811befa55e75e1094f8c0")
        add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2Ff%2F57a42b9002e19.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673423440&t=3e646b23ed5930e48b7bdec9c1cc4f8c")
        add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2Ff%2F57a42b9002e19.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673423440&t=3e646b23ed5930e48b7bdec9c1cc4f8c")
    }

    @Log("初始化时间")
    override fun initEvents() {
        Pgy.checkVersionUpdate(this)
//            mViewBinding.vm = mViewModel
        recyclerView?.apply {
            mAdapter =
                GridImageAdapter(
                    this@SampleActivity,
                    PicSelectorType.TYPE_IMAGE_VIDEO,
                    9,
                    picData,
                    1002,
                    true
                )
            adapter = mAdapter
        }

        recyclerViewNetImage?.apply {
            netImageAdapter = NetImageAdapter(
                ArrayList(),
                SizeUtils.dp2px(120F)
            ).apply {
                setOnItemClickListener { _, view, position ->
                    DragPhotoViewUtils.showDragPhotoView(
                        context = this@SampleActivity,
                        view = view as ImageView,
                        position = position,
                        imagePaths = netData,
                    )
                }
            }
            adapter = netImageAdapter
            netImageAdapter?.addData(netData)
        }

        tvCamera?.setOnClickListener {
            PicSelectorUtils.camera(this@SampleActivity,
                object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: ArrayList<LocalMedia>?) {
                        fenxi(result ?: return)
                        if (result.isNotEmpty()) {

                            val longTime = FileUtils.getFileLastModified(result[0].availablePath)
                            LogUtils.e("最后修改时间 = ${TimeUtils.millis2String(longTime)}")

//                            val srcBitmap = ImageUtils.getBitmap(result[0].availablePath)
//                            val desb = ImageUtils.addTextWatermark(
//                                srcBitmap,
//                                TimeUtils.getNowString(),
//                                SizeUtils.sp2px(25F).toFloat(),
//                                ColorUtils.getColor(R.color.color_primary),
//                                50F,
//                                50F,
//                                true
//                            )

                        }
                    }

                    override fun onCancel() {
                        "您拍照取消了".toastTipMiddle()
                    }

                })
        }
        setOnClickListener(R.id.tvSave, R.id.tvGet)
//        tvCamera?.setOnClickListener {
//            startActivity(GaoDeMapActivity::class.java)
//            setResult(RESULT_OK, Intent().apply {
//                putExtra("param", "传过来了啊啊")
//            })
//            finish()
//        }

//        ivImage?.setOnClickListener {
//            DragPhotoViewUtils.showSingleDragPhotoView(
//                context = this@SampleActivity,
//                url = netData[0]
//            )
//        }

//        tvTestSingleClick?.singleClick {
//           LogUtils.e("你好=============" + TimeUtils.getNowString())
//        }

    }

    @SingleClick
    override fun onClick(view: View) {
        when (view.id) {
            R.id.tvSave -> {
//                MMKVUtils.getInstance().encode("per",Person("原来是",19))
                MMKVUtils.getInstance().encode("winBean", WinBean("李天佑","890"))
            }
            R.id.tvGet -> {
               val p =  MMKVUtils.getInstance().decodeObj("winBean",WinBean::class.java)
                LogUtils.e(GsonUtils.toJson(p))
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            if (requestCode == 1002 || requestCode == PictureConfig.REQUEST_CAMERA) {
                val result = PictureSelector.obtainSelectorList(data)
                if (result.isNotEmpty()) {
//                    mAdapter?.data?.clear()
//                    mAdapter?.data?.addAll(result)
//                    mAdapter?.notifyItemRangeInserted(0, result.size)

                    runOnUiThread {
//                        val isMaxSize = result.size == mAdapter?.selectMax
//                        val oldSize: Int = mAdapter?.data?.size?:0
//                        mAdapter?.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
                        mAdapter?.data?.clear()
                        mAdapter?.data?.addAll(result)
//                        mAdapter?.notifyItemRangeInserted(0, result.size)
                        mAdapter?.notifyDataSetChanged()
                    }
                }
                fenxi(result)
//                ivImage?.setImageBitmap(ImageUtils.getBitmap(result[0].videoThumbnailPath))

            }
        } else if (resultCode == RESULT_CANCELED) {
            "您已取消".toastTipMiddle()
        }
    }

    private fun fenxi(result: ArrayList<LocalMedia>) {

        for (item in result) {
            LogUtils.e(
                "文件名=${item.fileName}  " +
                        "  是否压缩=${item.isCompressed} " +
                        "  压缩路径=${item.compressPath}  " +
                        "  初始路径=${item.path} " +
                        "  绝对路径=${item.realPath}  " +
                        "  是否裁剪=${item.isCut}" +
                        "  裁剪路径=${item.cutPath} " +
                        "  是否开启原图=${item.isOriginal}" +
                        "  初始路径文件大小=${FileUtils.getSize(item.path)}" +
                        "  绝对路径文件大小=${FileUtils.getSize(item.realPath)} " +
                        "  压缩后的文件的大小 = ${FileUtils.getSize(item.compressPath)} " +
                        "  原图路径 = ${item.originalPath} " +
                        "  沙盒路径 = ${item.sandboxPath} " +
                        "  水印路径 = ${item.watermarkPath} " +
                        "  原始宽高 = ${item.width} X ${item.height} " +
                        "  裁剪宽高 = ${item.cropImageWidth} X ${item.cropImageHeight} " +
                        "  文件时长 = ${item.duration} " +
                        "  视频缩略图 = ${item.videoThumbnailPath} " +
                        "  视频缩略大小 = ${FileUtils.getSize(item.videoThumbnailPath)} " +
                        "  最后修改时间 = ${TimeUtils.millis2String(FileUtils.getFileLastModified(item.realPath))} "//此处必须传入绝对路径
            )

        }
    }

    override fun getLayoutResId(): Int = R.layout.activity_sample_main

    override fun viewModelClass(): Class<SampleViewModel> = SampleViewModel::class.java

}